home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c
- Path: in2.uu.net!world!mv!usenet
- From: ENGR@GSSI.MV.COM (Michael Furman)
- Subject: Re: quick decision: is n a power of 2?
- Message-ID: <DLoyKB.C8t@mv.mv.com>
- Mime-Version: 1.0
- Organization: GSSI
- Date: Wed, 24 Jan 1996 15:19:23 GMT
- References: <Pine.OSF.3.91.960119114608.18779E-100000@io.UWinnipeg.ca>
- X-Newsreader: WinVN 0.93.10
- X-Nntp-Posting-Host: gssi.mv.com
-
- In article <Pine.OSF.3.91.960119114608.18779E-100000@io.UWinnipeg.ca>,
- wsimpson@uwinnipeg.ca says...
- >
- >Is there a fast way to decide whether a number n is a power of 2?
- >
- >In my problem
- >if ((high-low+1) is a power of 2)
- > {
- > do one thing
- > }
- >else
- > {
- > do another
- > }
- >e.g. low=0, high=7: 7-0+1 is a power of 2.
- >
- >The only thing I have thought of is that if n is power of 2
- >log(n)/log(2) is an integer
- >BUT this is going to be a SLOW computation. Needs to be fast.
- >
- >Since I am dealing with unsigned long ints, I guess I can just store all
- >31 powers of 2 in a table and compare to n. Though I don't know a fast
- >algorithm to compare a number to 31 numbers in an array.
- >
- >Perhaps there is a tricky nonportable way to see if I have power-of-2 by
- >looking at bits? (That is fine for this application)
-
- Just write:
- if((n & (n - 1)) == 0)
- ......................
-
- And I believe in case of unsigned n it is portable (but sould be checked
- carefully with standard).
-
-
-
- >
- >Thanks very much for any help.
- >
- >Bill Simpson
-
- --
- <<<<<<<< This is a copy of post to the newsgroup >>>>>>>>
- ---------------------------------------------------------------
- Michael Furman, (603)893-1109
- Geophysical Survey Systems, Inc. fax:(603)889-3984
- 13 Klein Drive - P.O. Box 97 engr@gssi.mv.com
- North Salem, NH 03073-0097 71543.1334@compuserve.com
- ---------------------------------------------------------------
-
-